from PySide6.QtWidgets import QApplication, QMessageBox, QTableWidgetItem
from PySide6.QtUiTools import QUiLoader
from PySide6.QtCore import QFile
import requests


class HTTPServer:
    def __init__(self):
        qfile_http = QFile("./ui/HTTP接口测试.ui")
        qfile_http.open(QFile.ReadOnly)
        qfile_http.close()

        self.ui = QUiLoader().load(qfile_http)
        self.set_defaults()

        self.ui.addbutton.clicked.connect(self.add_headers)
        self.ui.reducebutton.clicked.connect(self.remove_headers)
        self.ui.addbutton_2.clicked.connect(self.add_data)
        self.ui.reducebutton_2.clicked.connect(self.remove_data)
        self.ui.send_button.clicked.connect(self.send_request)
        self.ui.clearbutton.clicked.connect(self.clear_response)

    def set_defaults(self):
        # 设置默认的请求头 User-Agent
        self.ui.header_table.insertRow(0)  # 在第一行添加新行
        self.ui.header_table.setItem(0, 0, QTableWidgetItem("User-Agent"))
        self.ui.header_table.setItem(0, 1, QTableWidgetItem(
            "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Mobile Safari/537.36"))

    def send_request(self):
        http_method = self.ui.url_combobox.currentText()
        url = self.ui.url_textedit.toPlainText()
        param = self.ui.TextEdit_2.toPlainText()
        print("HTTP Method:", http_method)
        print("URL:", url)

        header = self.get_headers()
        print("header", header)

        params = self.get_params(param)
        print("params", params)

        data = self.get_data()
        print("data", data)

        if http_method == "GET":
            print("HTTP GET")
            self.get_request(http_method, url, header, params=None)
        if http_method == "POST":
            print("HTTP POST")
            self.post_request(http_method, url, header, data=None)

    def add_headers(self):
        """
        增加消息头
        :return:
        """
        currentRowCount = self.ui.header_table.rowCount()
        self.ui.header_table.insertRow(currentRowCount)
        self.ui.header_table.setItem(currentRowCount, 0, QTableWidgetItem("新名称"))
        self.ui.header_table.setItem(currentRowCount, 1, QTableWidgetItem("新值"))

    def remove_headers(self):
        """
        删除消息头
        :return:
        """
        selectedRows = self.ui.header_table.selectionModel().selectedRows()
        for row in sorted(selectedRows, reverse=True):
            self.ui.header_table.removeRow(row.row())

    def get_headers(self):
        """
        获取消息头
        :return:
        """
        headers = {}
        rows = self.ui.header_table.rowCount()
        print(rows)
        for row in range(rows):
            name_item_text = self.ui.header_table.item(row, 0).text() if self.ui.header_table.item(row, 0) else ''
            value_item_text = self.ui.header_table.item(row, 1).text() if self.ui.header_table.item(row, 1) else ''
            if name_item_text is not None and value_item_text is not None:
                headers[name_item_text.strip()] = value_item_text.strip()
        return headers

    def add_data(self):
        currentRowCount = self.ui.data_table.rowCount()
        self.ui.data_table.insertRow(currentRowCount)
        self.ui.data_table.setItem(currentRowCount, 0, QTableWidgetItem("新名称"))
        self.ui.data_table.setItem(currentRowCount, 1, QTableWidgetItem("新值"))

    def remove_data(self):
        selectedRows = self.ui.data_table.selectionModel().selectedRows()
        for row in sorted(selectedRows, reverse=True):
            self.ui.data_table.removeRow(row.row())

    def get_data(self):
        data = {}
        rows = self.ui.data_table.rowCount()
        print(rows)
        for row in range(rows):
            name_item_text = self.ui.data_table.item(row, 0).text() if self.ui.data_table.item(row, 0) else ''
            value_item_text = self.ui.data_table.item(row, 1).text() if self.ui.data_table.item(row, 1) else ''
            if name_item_text is not None and value_item_text is not None:
                data[name_item_text.strip()] = value_item_text.strip()
        return data

    def get_params(self, param_str):
        """
        解析参数字符串，返回字典
        """
        params = {}
        # 分割字符串以获取键值对
        pairs = param_str.split('&')
        for pair in pairs:
            if '=' in pair:
                name, value = pair.split('=', 1)  # 只分割第一个等号
                params[name] = value
        return params

    def clear_response(self):
        self.ui.TextEdit_3.clear()

    def post_request(self, http_method, url, header, data):
        try:
            response = requests.request(http_method, url, headers=header, data=data)
            self.ui.TextEdit_3.setPlainText(response.text)
            return response.text

        except Exception as e:
            print(e)

    def get_request(self, http_method, url, header, params):
        try:
            response = requests.request(http_method, url, headers=header, params=params)
            self.ui.TextEdit_3.setPlainText(response.text)
            return response.text


        except Exception as e:
            print(e)


app = QApplication([])
httpserver = HTTPServer()
httpserver.ui.show()
app.exec_()
